// components/xpicker/index.js
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        dict: {
            type: Array,
            required: true,
			value: function(){
				return []
			}
        },
        disabled: {
            type: Boolean,
			value: false
        },
        key: {
            type: String,
            required: true,
			value: ""
        },
        value: {
            type: String,
            required: true,
			value: ""
        },
        rangeKey: {
            type: String,
			value: "dictLabel"
        },
        valueKey: {
            type: String,
			value: "dictValue"
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        index: -1,
    },
    lifetimes: {
        // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
        attached: function () { 
            
        },
        ready: function () {
            
        },
        moved: function () { 
            //console.log("moved")
        },
        detached: function () { 
            //console.log("detached")
        },
    },
    observers: {
        'value': function(value) {
            let that = this;
            if(!value){
                this.setData({
                    index: -1
                })
                return
            }
            this.data.dict.forEach((item,index) => {
                if(that.data.value == item[that.data.valueKey]){
                    that.setData({
                        index: index
                    })
                }
            })
            // console.log(this.data.dict,this.data.value)
        },
        'dict': function(array) {
            let that = this;
            if(array.length<=0){
                this.setData({
                    index: -1
                })
                return
            }
            this.data.dict.forEach((item,index) => {
                if(that.data.value == item[that.data.valueKey]){
                    that.setData({
                        index: index
                    })
                }
            })
        }
    },
    /**
     * 组件的方法列表
     */
    methods: {
        bindPickerChange(e){
            this.setData({
                index: e.detail.value
            })
            let { dict, key, index, valueKey, rangeKey} = this.data;
            this.triggerEvent('pickerChagne', { key: key, value: dict[index][valueKey], label: dict[index][rangeKey] });
        }
    }
})
